package com.example.servicetest

import android.content.Intent
import android.database.Cursor
import android.graphics.*
import android.media.MediaPlayer
import android.media.audiofx.Visualizer
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextPaint
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.example.servicetest.ui.clip_image.ClipImageActivity
import com.example.servicetest.util.HexUtils
import java.lang.Integer.min
import java.util.*
import kotlin.math.max


class MainActivity : AppCompatActivity(),
    Visualizer.OnDataCaptureListener {

    private var mCursor: Cursor? = null

    private val PROJECTION = arrayOf(
        MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
        MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
        MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ALBUM_ID,
        MediaStore.Audio.Media.ARTIST_ID
    )

    val mBoxPaintSize = 2
    val mBoxColumnCount = 58

    private lateinit var  mCurrentMediaPlayer: MediaPlayer

    private lateinit var mVisualizer: Visualizer

    private lateinit var mDanceView:DanceView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MyTextUtils.init(applicationContext)
        setContentView(R.layout.activity_main)
        mDanceView = findViewById(R.id.danceView)
        requestPermissions(arrayOf(android.Manifest.permission.RECORD_AUDIO),1)
    }

    fun doClick(view: View) {
        when(view.id){

            R.id.btnStartService->{
                val ss = getAdjacentBoxes(4,5)
                ss
//                startService(Intent(this, MyService::class.java))
            }

            R.id.btnQuery->{
//                mCursor = openCursorAndGoToFirst(
//                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
//                    PROJECTION, "_id=17", null
//                )

                measureText("e")
                Log.i("lxc", "--------------------------------------------------")
                measureText("j")
            }

            R.id.btnPlay->{
                mCurrentMediaPlayer.start()
            }

            R.id.btn1->{
                startActivity(Intent(this,SecondActivity::class.java))
            }

            R.id.btn3->{

            }
            R.id.btn4->{
                startActivity(Intent(this, ClipImageActivity::class.java))
            }

            R.id.btnThirdActivity->{
                startActivity(Intent(this,ThirdActivity::class.java))
            }

            R.id.btn5->{
                val byteArray = "YHK".toByteArray()
                Log.i("deal-magic", HexUtils.bytesToHexString(byteArray)!!)

                Integer.toHexString(102).toByteArray()
                Log.i("deal-version", HexUtils.bytesToHexString(Integer.toHexString(1).toByteArray())!!)

                val commandByte = Integer.toHexString(102).toByte()
                Log.i("deal-command", commandByte.toString())

                val ss12 = Integer.toHexString(0x783cb9)
                Log.i("deal-color", HexUtils.bytesToHexString(ss12.toByteArray())!!)


                val ss = Color.parseColor("#783cb9")
                val ss16 = toHexEncoding(ss)
                val b = HexString2Bytes(ss16!!)
                val s = Bytes2HexString(b)!!
                Log.i("deal-color", s)


            }

        }
    }

    fun toHexEncoding(color: Int): String? {
        var R: String
        var G: String
        var B: String
        val sb = StringBuffer()
        R = Integer.toHexString(Color.red(color))
        G = Integer.toHexString(Color.green(color))
        B = Integer.toHexString(Color.blue(color))
        //判断获取到的R,G,B值的长度 如果长度等于1 给R,G,B值的前边添0
        R = if (R.length == 1) "0$R" else R
        G = if (G.length == 1) "0$G" else G
        B = if (B.length == 1) "0$B" else B
        sb.append("0x")
        sb.append(R)
        sb.append(G)
        sb.append(B)
        return sb.toString()
    }

    /**
     * 将两个ASCII字符合成一个字节；
     * 如："EF"--> 0xEF
     * @param src0 byte
     * @param src1 byte
     * @return byte
     */
    fun uniteBytes(src0: Byte, src1: Byte): Byte {
        var _b0 = java.lang.Byte.decode("0x" + String(byteArrayOf(src0))).toByte()
        _b0 = (_b0.toInt() shl 4).toByte()
        val _b1 = java.lang.Byte.decode("0x" + String(byteArrayOf(src1))).toByte()
        return (_b0.toInt() xor _b1.toInt()).toByte()
    }


    /**
     * 将指定字符串src，以每两个字符分割转换为16进制形式
     * 如："2B44EFD9" –> byte[]{0x2B, 0×44, 0xEF, 0xD9}
     * @param src String
     * @return byte[]
     */
    fun HexString2Bytes(src: String): ByteArray {
        val ret = ByteArray(src.length / 2)
        val tmp = src.toByteArray()
        for (i in 0 until tmp.size/ 2) {
            ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1])
        }
        return ret
    }

    /**
     * 将指定byte数组以16进制的形式打印到控制台
     * @param hint String
     * @param b byte[]
     * @return void
     */
    fun printHexString(hint: String?, b: ByteArray) {
        print(hint)
        for (i in b.indices) {
            var hex = Integer.toHexString(b[i].toInt() and 0xFF)
            if (hex.length == 1) {
                hex = "0$hex"
            }
            print(hex.uppercase(Locale.getDefault()) + " ")
        }
        println("")
    }

    /**
     *
     * @param b byte[]
     * @return String
     */
    fun Bytes2HexString(b: ByteArray): String? {
        var ret = ""
        for (i in b.indices) {
            var hex = Integer.toHexString(b[i].toInt() and 0xFF)
            if (hex.length == 1) {
                hex = "0$hex"
            }
            ret += hex.uppercase(Locale.getDefault())
        }
        return ret
    }


    private fun getAdjacentBoxes(rowIndex:Int,columnIndex:Int):List<Point>{
        var rowStart = 0
        var rowEnd = 0
        var columnStart = 0
        var columnEnd = 0
        val points = mutableListOf<Point>()

        when(mBoxPaintSize%2 == 0){
            true->{
                val extendIndex = mBoxPaintSize/2
                rowStart = max(rowIndex-extendIndex+1,0)
                rowEnd = Integer.min(rowIndex + extendIndex, mBoxColumnCount-1)

                columnStart = max(columnIndex-extendIndex+1,0)
                columnEnd = min(columnIndex + extendIndex+1, mBoxColumnCount-1)
            }
            false->{
                val extendIndex = (mBoxPaintSize - 1)/2

                rowStart = max(rowIndex-extendIndex,0)
                rowEnd = min(rowIndex + extendIndex, mBoxColumnCount-1)

                columnStart = max(columnIndex-extendIndex,0)
                columnEnd = min(columnIndex + extendIndex, mBoxColumnCount-1)

            }
        }

        for(row in rowStart..rowEnd){
            for(column in columnStart .. columnEnd){
                points.add(Point(row,column))
            }
        }
        return points
    }

    private fun openCursorAndGoToFirst(
        uri: Uri, projection: Array<String>,
        selection: String, selectionArgs: Array<String>?
    ): Cursor? {
        val c = contentResolver.query(
            uri, projection,
            selection, selectionArgs, null
        ) ?: return null
        if (!c.moveToFirst()) {
            c.close()
            return null
        }
        return c
    }

    override fun onWaveFormDataCapture(
        visualizer: Visualizer?,
        waveform: ByteArray?,
        samplingRate: Int
    ) {

    }

    override fun onFftDataCapture(visualizer: Visualizer, fft: ByteArray, samplingRate: Int) {
        Log.i("TAG", "onFftDataCapture: ${fft}")
        mDanceView.updateFFT(fft)
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode == 1){
            try {
                val fikkDes = assets.openFd("zxa.mp3")
                mCurrentMediaPlayer =  MediaPlayer()

                mVisualizer = Visualizer(mCurrentMediaPlayer.audioSessionId)
                mVisualizer.captureSize = Visualizer.getCaptureSizeRange()[1]
                mVisualizer.setDataCaptureListener(this@MainActivity, Visualizer.getMaxCaptureRate() / 2, false, true)
                mVisualizer.enabled = true

                mCurrentMediaPlayer.reset()
                mCurrentMediaPlayer.setDataSource(fikkDes)
                mCurrentMediaPlayer.prepare()
            }catch (e:Exception){
                e
            }
        }
    }

    private fun measureText(str: String?) {
        if (str == null) {
            return
        }
        val mPaint = TextPaint()
        val width2: Float = mPaint.measureText(str)
        Log.i("lxc", "width2 ---> $width2")
        val fontMetrics: Paint.FontMetrics = mPaint.fontMetrics
        val height1: Float =
            Math.abs(fontMetrics.leading + fontMetrics.ascent) + fontMetrics.descent
        Log.i("lxc", "height1 ---> $height1")
        val rect = Rect()
        mPaint.getTextBounds(str, 0, str.length, rect)
        val width3 = rect.width()
        val height2 = rect.height()
        Log.i("lxc", "width3 ---> $width3")
        Log.i("lxc", "height2 ---> $height2")
        val textPath = Path()
        mPaint.getTextPath(str, 0, str.length, 0.0f, 0.0f, textPath)
        val boundsPath = RectF()
        textPath.computeBounds(boundsPath, true)
        val width4 = boundsPath.width()
        val height3 = boundsPath.height()
        Log.i("lxc", "width4 ---> $width4")
        Log.i("lxc", "height3 ---> $height3")
    }

}